import LangTags, { LangTag } from '@/components/LangTags';
import * as api from '@/services/product';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button } from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import Form from './components/Form';

const ProductList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.Product | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');

  const { reloadProducts, reloadVpnGroupTrees } = useModel(
    'useGlobalModel',
    (model) => ({
      reloadProducts: model.reloadProducts,
      reloadVpnGroupTrees: model.reloadVpnGroupTrees,
    }),
  );

  const handleFormSubmit = async (record: API.Product) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();

      //更新产品信息全局缓存
      await reloadProducts();
      //await reloadVpnGroupTrees();
    }
  };

  let columns: ProColumns<API.Product>[] = [
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: 'ID',
      align: 'center',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '域名',
      dataIndex: 'domain',
    },
    {
      title: '支持语言',
      dataIndex: 'langs',
      render: (_, record) => <LangTags values={record.langs} />,
    },
    {
      title: '默认语言',
      align: 'center',
      dataIndex: 'defaultLang',
      render: (_, record) => <LangTag value={record.defaultLang} />,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('product_update')) {
          cmps.push(
            <a
              key="edit"
              onClick={(e) => {
                setFormVisible(true);
                setCurrent(record);
              }}
            >
              编辑
            </a>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        search={false}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        pagination={false}
        toolBarRender={() => {
          if (hasRight('product_create')) {
            return [
              <Button
                type="primary"
                key="create"
                onClick={() => {
                  setFormVisible(true);
                }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ];
          }
          return [];
        }}
        request={api.list}
      />
      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default ProductList;
